// Project name:JavaRedis
// Creator:muhong
// Date time:2022/12/9,11:56 下午
// Name:EchoHandler

package org.gmh.server.v2;

import org.gmh.channel.ChannelHandler;
import org.gmh.channel.handler.ChannelHandlerContext;
import org.gmh.channel.handler.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;

@ChannelHandler.Sharable
public class EchoHandler extends ChannelInboundHandlerAdapter {
    private final static Logger logger = LoggerFactory.getLogger(EchoHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        logger.info("hand data msg");
        if (msg instanceof ByteBuffer) {
            ByteBuffer byteBuffer = (ByteBuffer) msg;
            //
            byteBuffer.flip();
            int size = byteBuffer.remaining();
            logger.info("hand data from client:" + size);
            byte[] contentByte = new byte[size];
            byteBuffer.get(contentByte);
            logger.info("hand data from client:" + new String(contentByte));
            byteBuffer.compact();
            //
            ctx.write(contentByte);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.warn("There is an exception happened:", cause);
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        logger.info("Channel registered");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        logger.info("Channel active");
    }
}
